package com.glodon.paas.databag.observer;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.glodon.paas.databag.model.Databag;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

/**
 * 搜索服务观察者.
 * 
 * @author botao.liao
 * 
 */
@Component("searchDatabagObserver")
public class SearchDatabagObserver implements DatabagObserver {
    private Logger logger = LoggerFactory.getLogger(SearchDatabagObserver.class);
    @Value("${api.internal.search.url}")
    private String searchInternalUrl;
    private ExecutorService executor = Executors.newFixedThreadPool(1);

    @Override
    public void onSuccess(final Databag databag) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                String url = searchInternalUrl.trim() + "/bag/" + databag.getId();
                WebResource resource = Client.create().resource(url);
                ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class);
                if (c.getStatus() != 200) {
                    logger.error("failed to notify search observer.", c.getEntity(String.class));
                }
            }
        });
    }
}
